package com.springBoot.controller;


import com.springBoot.entity.ObjectsEntity;
import com.springBoot.exception.BusinessFailureException;
import com.springBoot.requestdto.ObjectForm;
import com.springBoot.service.ObjectsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/file-obj")
public class ObjectController {

    @Autowired
    private ObjectsService objService;

    @GetMapping("/retrieve-by-params")
    public List<ObjectsEntity> retrieveByParams(ObjectsEntity params){
        if(params == null){
            params = new ObjectsEntity();
        }
        ObjectsEntity cusEntity = new ObjectsEntity();
        BeanUtils.copyProperties(params, cusEntity);
        return objService.retrieveByParams(cusEntity);
    }

    @PostMapping("/update")
    public ObjectsEntity updateObj(@RequestBody ObjectsEntity form){
        ObjectsEntity cusEntity = new ObjectsEntity();
        BeanUtils.copyProperties(form, cusEntity);
        return objService.updateObj(cusEntity);
    }

    @DeleteMapping("/delete")
    public void deleteObj(ObjectsEntity param){
        if(param == null){
            param = new ObjectsEntity();
        }
        ObjectsEntity cusEntity = new ObjectsEntity();
        BeanUtils.copyProperties(param, cusEntity);
        objService.deleteObj(cusEntity);
    }

    @PostMapping("insert")
    public ObjectsEntity insertObj(@RequestBody @Valid ObjectForm form, Errors errors){
        if (errors.hasErrors()) {
            // 当form中存在验证错误，则抛出业务错误，将验证信息输出。
            throw new BusinessFailureException(errors);
        }
        ObjectsEntity cusEntity = new ObjectsEntity();
        BeanUtils.copyProperties(form, cusEntity);
        return objService.InsertNewObj(cusEntity);
    }
}
